﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Data;
using TVMCORP.TVS.UTIL.Utilities;
using TVMCORP.TVS.UTIL;
using Microsoft.SharePoint.WebControls;

namespace TVMCORP.TVS.ControlTemplates.TVMCORP.TVS
{
    public partial class RepaymentEditForm : UserControl
    {
        private string viewUrl = string.Format(@"javascript:NewItem2(event,'{0}/{1}?ListId={2}{3}');javascript:return false;", SPContext.Current.Web.Url, SPContext.Current.List.Forms[PAGETYPE.PAGE_EDITFORM].Url, SPContext.Current.List.ID, "&ID={0}");

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            //Ridrect page
            SPFieldUserValue createdBy = new SPFieldUserValue(SPContext.Current.Web, SPContext.Current.ListItem["Author"].ToString());
            if (SPContext.Current.Web.CurrentUser.LoginName != createdBy.User.LoginName)
            {
                var viewUrl = string.Format(@"{0}/{1}?ID={2}&IsDlg=1", SPContext.Current.Web.Url, SPContext.Current.List.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url, SPContext.Current.ListItem.ID);
                Response.Redirect(viewUrl);
            }
            //
            SPRibbon ribbon = SPRibbon.GetCurrent(this.Page);
            if (ribbon != null)
            {
                ribbon.TrimById("Ribbon.ListForm.Edit.Commit");
            }

            //
            btnSave.Click += new EventHandler(btnSave_Click);
            linkButtonAdd.Click += new EventHandler(AddRequestDetail);
            repeaterRequestDetail.ItemDataBound += new RepeaterItemEventHandler(repeaterRequestDetail_ItemDataBound);

            //
            InitData();
        }

        private void LoadTypeOfRepayment()
        {
            SPFieldChoice typeOfRepayments = (SPFieldChoice)SPContext.Current.List.Fields.GetField("TypeOfRepayment");
            if (typeOfRepayments != null)
            {
                rdbListTypeOfRepayment.DataSource = typeOfRepayments.Choices;
                rdbListTypeOfRepayment.DataBind();
            }
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
                return;

            UpdateRequest();

            this.Page.Response.Clear();
            this.Page.Response.Write(
            string.Format(System.Globalization.CultureInfo.InvariantCulture, @"<script type='text/javascript'> window.frameElement.commonModalDialogClose(1, '{0}');</script>", ""));
            this.Page.Response.End();
        }

        void AddRequestDetail(object sender, EventArgs e)
        {
            DataTable dataTable = MakeRequestDetail();
            repeaterRequestDetail.DataSource = dataTable;
            repeaterRequestDetail.DataBind();
        }

        void repeaterPurchaseReference_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DataRowView rowView = (DataRowView)e.Item.DataItem;
            if (rowView != null)
            {
                Literal literalOrder = e.Item.FindControl("literalOrder") as Literal;
                literalOrder.Text = (e.Item.ItemIndex + 1).ToString();

                LinkButton linkButtonReferenceTitle = e.Item.FindControl("linkButtonReferenceTitle") as LinkButton;
                linkButtonReferenceTitle.Text = rowView["Title"].ToString();
                linkButtonReferenceTitle.OnClientClick = string.Format(viewUrl, rowView["ID"]);

                Literal literalReferenceDate = e.Item.FindControl("literalReferenceDate") as Literal;
                literalReferenceDate.Text = Convert.ToDateTime(rowView["DateRequest"].ToString()).ToString("dd/MM/yyyy");

                Literal literalReferenceUser = e.Item.FindControl("literalReferenceUser") as Literal;
                SPFieldUserValue userValue = new SPFieldUserValue(SPContext.Current.Web, rowView["UserRequest"].ToString());
                literalReferenceUser.Text = userValue.User.Name;

                Literal literalReferenceDepartment = e.Item.FindControl("literalReferenceDepartment") as Literal;
                literalReferenceDepartment.Text = rowView["DepartmentRequest"].ToString();
            }
        }

        void repeaterRequestDetail_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DataRowView rowView = (DataRowView)e.Item.DataItem;
            if (rowView != null)
            {
                HiddenField hiddenFieldId = e.Item.FindControl("hiddenFieldId") as HiddenField;
                hiddenFieldId.Value = rowView["ID"].ToString();

                Literal literalOrder = e.Item.FindControl("literalOrder") as Literal;
                literalOrder.Text = (e.Item.ItemIndex + 1).ToString();

                TextBox txtProductName = e.Item.FindControl("txtContent") as TextBox;
                txtProductName.Text = rowView["Content"].ToString();

                TextBox txtAmount = e.Item.FindControl("txtAmount") as TextBox;
                txtAmount.Text = string.IsNullOrEmpty(rowView["Amount"].ToString()) ? string.Empty : Convert.ToDouble(rowView["Amount"]).ToString("#,###");
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Load detail
                DataTable requestDetail = LoadRequestDetail();
                if (requestDetail != null && requestDetail.Rows.Count > 0)
                {
                    repeaterRequestDetail.DataSource = requestDetail;
                    repeaterRequestDetail.DataBind();
                }
            }
        }

        #region Private Functions

        private void UpdateRequest()
        {
            SPFieldLookupValueCollection requestDetails = new SPFieldLookupValueCollection();
            var requestDetailList = Utility.GetListFromURL(Constants.REQUEST_DETAIL_LIST_URL, SPContext.Current.Web);
            foreach (RepeaterItem requestDetail in repeaterRequestDetail.Items)
            {
                HiddenField hiddenFieldId = requestDetail.FindControl("hiddenFieldId") as HiddenField;
                TextBox txtContent = requestDetail.FindControl("txtContent") as TextBox;
                TextBox txtAmount = requestDetail.FindControl("txtAmount") as TextBox;

                if (!string.IsNullOrEmpty(hiddenFieldId.Value))
                {
                    if (!string.IsNullOrEmpty(txtContent.Text))
                    {
                        var spFieldLookupValue = UpdateRequestDetail(requestDetailList, int.Parse(hiddenFieldId.Value), txtContent.Text, txtAmount.Text.Replace(",", string.Empty));
                        requestDetails.Add(spFieldLookupValue);
                    }
                    else
                    {
                        SPListItem RequestDetailItem = requestDetailList.GetItemById(int.Parse(hiddenFieldId.Value));
                        RequestDetailItem.Delete();
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(txtContent.Text))
                    {
                        SPListItem RequestDetailItem = requestDetailList.AddItem();
                        RequestDetailItem[SPBuiltInFieldId.Title] = txtContent.Text;
                        RequestDetailItem["Amount"] = txtAmount.Text.Replace(",", string.Empty);
                        RequestDetailItem.Update();
                        SPFieldLookupValue spFieldLookupValue = new SPFieldLookupValue(RequestDetailItem.ID, RequestDetailItem.Title);
                        requestDetails.Add(spFieldLookupValue);
                    }
                }
            }

            SPListItem currentItem = SPContext.Current.ListItem;
            currentItem["Currency"] = rdbVND.Text;
            if (rdbUSD.Checked)
                currentItem["Currency"] = rdbUSD.Text;

            currentItem[SPBuiltInFieldId.Title] = ffTitle.Value;
            currentItem["RequestDetail"] = requestDetails;
            currentItem["AmountRepayment"] = txtAmountRepayment.Text.Replace(",", string.Empty);
            currentItem["TypeOfRepayment"] = rdbListTypeOfRepayment.SelectedValue;

            SaveButton.SaveItem(SPContext.Current, false, string.Empty);
        }

        private SPFieldLookupValue UpdateRequestDetail(SPList requestDetailList, int id, string content, string amount)
        {
            try
            {
                SPFieldLookupValue spFieldLookupValue = null;
                SPListItem requestDetailItem = requestDetailList.GetItemById(id);
                if (requestDetailItem != null)
                {
                    requestDetailItem[SPBuiltInFieldId.Title] = content;
                    requestDetailItem["Amount"] = amount;
                    requestDetailItem.Update();
                    spFieldLookupValue = new SPFieldLookupValue(requestDetailItem.ID, requestDetailItem.Title);
                }
                return spFieldLookupValue;
            }
            catch
            {
                return null;
            }
        }

        private void InitData()
        {
            literalDateRequestValue.Text = Convert.ToDateTime(SPContext.Current.ListItem["DateRequest"].ToString()).ToString("dd/MM/yyyy");

            string currency = string.Empty;
            if (SPContext.Current.ListItem["Currency"] != null)
            {
                currency = SPContext.Current.ListItem["Currency"].ToString();
            }
            rdbVND.Checked = true;
            if (currency == rdbUSD.Text)
                rdbUSD.Checked = true;

            if (SPContext.Current.ListItem["AmountRepayment"] != null)
            {
                txtAmountRepayment.Text = string.IsNullOrEmpty(SPContext.Current.ListItem["AmountRepayment"].ToString()) ? string.Empty : Convert.ToDouble(SPContext.Current.ListItem["AmountRepayment"]).ToString("#,###");
            }

            //
            LoadTypeOfRepayment();
            if (SPContext.Current.ListItem["TypeOfRepayment"] != null)
            {
                rdbListTypeOfRepayment.SelectedValue = SPContext.Current.ListItem["TypeOfRepayment"].ToString();
            }
            //Set discussion link url
            hyperLinkViewDiscussion.NavigateUrl = SPContext.Current.Site.MakeFullUrl(string.Format("{0}/_layouts/TVMCORP.TVS/DiscussionResolver.aspx?List={1}&ID={2}", SPContext.Current.Web.ServerRelativeUrl, SPContext.Current.ListId, SPContext.Current.ListItem.ID));
        }


        private DataTable MakeRequestDetail()
        {
            DataTable dataTable = new DataTable();
            DataColumn[] dataColumn = new DataColumn[]{
                new DataColumn("ID"),
                new DataColumn("Content"),
                new DataColumn("Amount")
            };
            dataTable.Columns.AddRange(dataColumn);

            foreach (RepeaterItem RequestDetail in repeaterRequestDetail.Items)
            {
                HiddenField hiddenFieldId = RequestDetail.FindControl("hiddenFieldId") as HiddenField;
                TextBox txtContent = RequestDetail.FindControl("txtContent") as TextBox;
                TextBox txtAmount = RequestDetail.FindControl("txtAmount") as TextBox;

                DataRow row = dataTable.NewRow();
                if (!string.IsNullOrEmpty(txtContent.Text))
                {
                    row[0] = hiddenFieldId.Value;
                    row[1] = txtContent.Text;
                    row[2] = txtAmount.Text;
                    dataTable.Rows.Add(row);
                }
            }

            DataRow emptyRow = dataTable.NewRow();
            emptyRow[0] = string.Empty;
            emptyRow[1] = string.Empty;
            emptyRow[2] = string.Empty;
            dataTable.Rows.Add(emptyRow);
            ViewState["RequestDetail"] = dataTable;

            return dataTable;
        }

        private DataTable LoadRequestDetail()
        {
            DataTable dataTable = dataTable = new DataTable();
            DataColumn[] dataColumn = new DataColumn[]{
                new DataColumn("ID"),
                new DataColumn("Content"),
                new DataColumn("Amount")
            };
            dataTable.Columns.AddRange(dataColumn);

            var RequestDetailList = Utility.GetListFromURL(Constants.REQUEST_DETAIL_LIST_URL, SPContext.Current.Web);
            SPFieldLookupValueCollection RequestDetails = SPContext.Current.ListItem["RequestDetail"] as SPFieldLookupValueCollection;
            foreach (var RequestDetail in RequestDetails)
            {
                SPListItem listItem = RequestDetailList.GetItemById(RequestDetail.LookupId);
                if (listItem != null)
                {
                    DataRow row = dataTable.NewRow();
                    row[0] = listItem[SPBuiltInFieldId.ID].ToString();
                    row[1] = listItem[SPBuiltInFieldId.Title].ToString();
                    row[2] = listItem["Amount"] != null ? listItem["Amount"].ToString() : string.Empty;
                    dataTable.Rows.Add(row);
                }
            }

            return dataTable;
        }

        private DataTable LoadPurchaseReferences()
        {
            DataTable dataTable = dataTable = new DataTable();
            DataColumn[] dataColumn = new DataColumn[]{
                new DataColumn("Title"),
                new DataColumn("DateRequest"),
                new DataColumn("UserRequest"),
                new DataColumn("DepartmentRequest"),
                new DataColumn("ID")
            };
            dataTable.Columns.AddRange(dataColumn);

            var purchaseList = SPContext.Current.List;
            SPFieldLookupValueCollection purchaseReferences = SPContext.Current.ListItem["References"] as SPFieldLookupValueCollection;
            if (purchaseReferences != null)
            {
                foreach (var purchaseReference in purchaseReferences)
                {
                    SPListItem listItem = purchaseList.GetItemById(purchaseReference.LookupId);
                    if (listItem != null)
                    {
                        DataRow row = dataTable.NewRow();
                        row[0] = listItem[SPBuiltInFieldId.Title].ToString();
                        row[1] = listItem["DateRequest"].ToString();
                        row[2] = listItem["UserRequest"].ToString();
                        row[3] = listItem["DepartmentRequest"] != null ? listItem["DepartmentRequest"].ToString() : string.Empty;
                        row[4] = listItem.ID;
                        dataTable.Rows.Add(row);
                    }
                }
            }
            return dataTable;
        }
        #endregion Private Functions
    }
}
